package com.generalbackend.role.util;

import com.generalbackend.role.model.entity.Permission;
import org.dom4j.Element;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static com.generalbackend.common.constants.Constants.*;

/**
 * @author tim.xie
 * @date 2021/12/13 16:46
 */
public class PermissionXmlParseUtil {

    public static List<Permission> getPermissions(Element root, String parentId) {
        ArrayList<Permission> list = new ArrayList<>();
        for (Iterator<Element> it = root.elementIterator(); it.hasNext();) {
            Element menu = it.next();
            Permission permission = new Permission();
            for (Iterator<Element> itElement = menu.elementIterator(); itElement.hasNext();) {
                Element next = itElement.next();
                if(next.getName().equals(ID)) {
                    permission.setId(next.getStringValue());
                } else if (next.getName().equals(NAME)) {
                    permission.setName(next.getStringValue());
                } else if (next.getName().equals(URL)) {
                    permission.setUrl(next.getStringValue());
                } else if (next.getName().equals(SORT)) {
                    permission.setSort(Integer.parseInt(next.getStringValue()));
                } else if (next.getName().equals(TYPE)) {
                    permission.setType(Integer.parseInt(next.getStringValue()));
                } else if (next.getName().equals(ICON)) {
                    permission.setIcon(next.getStringValue());
                } else if (next.getName().equals(MODULE)) {
                    permission.setModule(Integer.parseInt(next.getStringValue()));
                } else if (next.getName().equals(DESCRIPTION)) {
                    permission.setDescription(next.getStringValue());
                } else if (next.getName().equals(__MENU__)) {
                    list.addAll(getPermissions(next, permission.getId()));
                }
                if(parentId!=null) {
                    permission.setParentId(parentId);
                }
            }
            list.add(permission);
        }
        return list;
    }

}
